# Copyright 2011, Geoffrey Spear
# Licensed under the Apache 2.0 license; see the LICENSE file.
import os
from google.appengine.ext.db import metadata
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import namespace_manager
from google.appengine.api import memcache
from google.appengine.ext.webapp import template

class GaeDSVHandler(webapp.RequestHandler):
    def get(self):
        nsdata = {}
        namespaces = memcache.get('gaedsv_ns_list')
        if namespaces is None:
            namespaces = metadata.Namespace.all().fetch(100)
            memcache.set('gaedsv_ns_list', namespaces)
            
        for ns in namespaces:
            nsn = ns.namespace_name if ns.namespace_name != "" \
                  else "default"

            kinds = memcache.get('gaedsv_kinds_' + ns.namespace_name)
            if kinds is None:
                namespace_manager.set_namespace(ns.namespace_name)
                kinds = metadata.Kind.all().fetch(100)
                namespace_manager.set_namespace('')
                memcache.set('gaedsv_kinds_' + ns.namespace_name,
                             kinds)
            nsdata[nsn] = kinds

        tv = {'nsdata' : nsdata,
            }
        
        path = os.path.join(os.path.dirname(__file__), 'templates', 'nslist.html')
        self.response.out.write(template.render(path, tv))

application = webapp.WSGIApplication([('/_gaedsv/', GaeDSVHandler),
                                      ],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
